<template>
    <div class="component-upload-image">
        <canvas id="mycanvas" style="display: none"></canvas>
<!--        <el-upload :http-request="beforeUpload" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed"-->
<!--            name="file" :show-file-list="false" :file-list="fileList" class="upload-demo" drag action="" ref="uploadRef"-->
<!--            multiple>-->
<!--            <img v-if="videoForm.showVideoPath && !videoFlag" :src="videoForm.showVideoPath" ref="upvideo"  mode="aspectFill"-->
<!--                class="avatar video-avatar" controls="controls">-->
<!--            </img>-->
<!--            <template v-else-if="!videoForm.showVideoPath && !videoFlag">-->
<!--                <i class="el-icon-upload"></i>-->
<!--                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
<!--            </template>-->
<!--            <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent"-->
<!--                style="margin-top: 7px"></el-progress>-->
<!--            <div class="el-upload__tip" slot="tip">只能上传jpeg/jpg/png文件，且不超过{{ fileSize }}MB</div>-->
<!--        </el-upload>-->

      <el-upload :http-request="beforeUpload" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed"
      name="file"  :file-list="fileList" class="upload-demo" :on-remove="handleRemove" :before-remove="beforeRemove"
       action="" ref="uploadRef"
      multiple >
        <el-button size="small" type="primary">点击上传</el-button>
<!--        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
      </el-upload>

      <!-- <el-upload
  class="upload-demo"
  action="https://jsonplaceholder.typicode.com/posts/"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  multiple
  :limit="1"
  :on-exceed="handleExceed"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
</el-upload> -->
      

<!--        <el-button v-if="isShowBtn && videoForm.showVideoPath" class="mt-20" plain round @click="handleDelete"-->
<!--            size="small" type="primary">重新上传<i class="el-icon-upload el-icon&#45;&#45;right"></i></el-button>-->
    </div>
</template>

<script>

let cdnUrl = 'https://image.cnslpa.com/'
let OSS = require('ali-oss');

export default {
    name: 'OssUploadImagButton',
    props: {
        value: [String, Object, Array],
        // 图片数量限制
        limit: {
            type: Number,
            default: 1,
        },
        // 大小限制(MB)
        fileSize: {
            type: Number,
            default: 5120,
        },
        fileType: {
            type: Array,
            default: () => ["image/*"],
        },
        // 是否显示提示
        isShowTip: {
            type: Boolean,
            default: true,
        },
        // 是否显示进度条
        isShowUploadVideo: {
            type: Boolean,
            default: false,
        },
        // 是否显示重新上传按钮
        isShowBtn: {
            type: Boolean,
            default: true,
        },
    },
    data() {
        return {
            fileTypeTemp: [],
            client: null,
            url: "",
            dialogImageUrl: "",
            dialogVisible: false,
            fileList: [],
            videoForm: {
                showVideoPath: "", //回显的变量
                size:"",
            },
            videoFlag: false,
            videoUploadPercent: 0,
            isCancel: false,
            loading: null,
        };
    },
    watch: {
        value: {
            handler(val) {
                if (val) {
                    console.log(val);
                    // 首先将值转为数组
                    const list = Array.isArray(val) ? val : this.value.split(",");
                    if(list.length>0){
                        this.videoForm.showVideoPath = val[0].url;
                    // 然后将数组转为对象数组
                    this.fileList = list.map((item) => {
                        if (typeof item === "string") {
                            item = { name: item, url: item };
                        }
                        return item;
                    });
                    }else{
                        this.fileList = [];
                    return [];
                    }
                    
                } else {
                    this.fileList = [];
                    return [];
                }
            },
            deep: true,
            immediate: true,
        },
    },
    computed: {
        // 是否显示提示
        showTip() {
            return this.isShowTip && (this.fileTypeTemp || this.fileSize);
        },
    },
    methods: {
        initImgUrl(url) {
            this.initUpLoad();
            console.log(url);
            if(url){
                //初始化fileList；
                this.fileList = [];
                //获取文件名
                let fileName = this.getFileNameWithoutSuffix(url)
                this.fileList.push({
                    name: fileName,
                    url: url,
                });
                console.log("this.fileList",this.fileList)
            }
            this.videoForm.showVideoPath = url;
        },
        /**
     * 获取文件后缀名
     */
        getFileName(name) {
            const nameArr = name.split('.')
            const len = nameArr.length
            return len ? nameArr[len - 1] : ''
        },
        //获取除了后缀名的文件名
        getFileNameWithoutSuffix(name) {
            const nameArr = name.split('.')
            const len = nameArr.length
            let nameStr = len ? nameArr.slice(0, len - 1).join('.') : ''
            //去掉所有空格
            nameStr = nameStr.replace(/\s+/g, '')
            return nameStr
        },
        // 初始化OSS
        async initOSS() {
            await this.$http({
                url: this.$http.adornUrl('/sys/oss/aliOss/info'),
                method: 'get',
                params: this.$http.adornParams()
            }).then(({ data }) => {
                if (data && data.code === 0) {
                    console.log(data)
                    this.client = new OSS({
                        region: data.ossConfig.region,
                        accessKeyId: data.ossConfig.accessKeyId,
                        accessKeySecret: data.ossConfig.accessKeySecret,
                        bucket: data.ossConfig.bucket,
                        secure: true
                    });
                    console.log(this.client)
                }
            })

        },
        //自定义上传方法..
        async Upload(file) {
            // 创建OSS实例
            await this.initOSS();

            let client = this.client;
            console.log(file);
            this.isCancel = false;

            console.log("this.getFileName===>",this.getFileNameWithoutSuffix(file.file.name));
            let realFileName = this.getFileNameWithoutSuffix(file.file.name) + this.uuid();
            const fileName = `files/img/${realFileName}.${file.file.name.split('.').pop()}`;
            const progress = (p) => {
                this.videoFlag = true;
                this.videoUploadPercent = Number((Number(p) * 100).toFixed(1));
            };
            client.multipartUpload(fileName, file.file, {
                progress,
                // 设置并发上传的分片数量。
                parallel: 4,
                // 设置分片大小。默认值为1 MB，最小值为100 KB。
                partSize: 5 * 1024 * 1024,
            }).then((res) => {
                console.log(res, "res");
                this.videoFlag = false;
                if (res.name) {
                    this.videoForm.showVideoPath = cdnUrl + res.name;
                    console.log(this.videoForm);
                    // this.fileList.push({
                    //     name: realFileName,
                    //     url: cdnUrl + res.name,
                    // });
                    console.log("fileList======>",this.fileList)

                    this.$emit("input", {
                        url: this.videoForm.showVideoPath,
                        duration: this.duration,
                        size: this.videoForm.size,
                        name:realFileName
                    });
                  
                    this.loading.close();
                } else {
                    this.$message.error("上传文件失败，请重试");
                    // this.loading.close();
                    this.handleDelete();
                }
            })
                .catch((err) => {
                    console.log(err);
                    if (err.name == 'cancel') {
                        this.$message.error('上传取消');
                    } else {
                        this.$message.error(err);
                    }
                    this.handleDelete();
                });
        },
        handleDelete() {
            this.initUpLoad();
            this.$emit("input", this.videoForm.showVideoPath, this.duration); // 清除已上传的文件
            this.loading.close();
        },
        initUpLoad() {
            this.isCancel = true;
            this.videoFlag = false;
            this.fileList = [];
            this.$refs.uploadRef.clearFiles();
            this.duration = 0;
            this.videoForm.showVideoPath = "";
        },

        // 上传前
        beforeUpload(file) {
            this.fileTypeTemp = JSON.parse(JSON.stringify(this.fileType));
            var fileSize = file.file.size / 1024 / 1024 < this.fileSize; //控制大小  修改50的值即可
            //如果this.fileType后边是*号，只需要判断前边的部分即可
            this.videoForm.size=file.file.size/1024;
            console.log(this.fileTypeTemp);

            if (this.fileTypeTemp.indexOf(file.file.type.split("/")[0] + "/*") != -1) {
                //如果包含，则将this.fileTypeTemp替换为当前文件的类型
                this.fileTypeTemp = [file.file.type];

            }
            console.log(file.file.type);

            if (
                this.fileTypeTemp.indexOf(file.file.type) == -1 //控制格式
            ) {
                this.$message.error(
                    `文件格式不正确, 请上传${this.fileTypeTemp.join("/")}格式文件!`
                );
                this.handleDelete();

                return false;
            }
            if (!fileSize) {
                this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
                this.handleDelete();
                return false;
            }
            // 一开始设置的全屏遮罩层，考虑到用户可能想取消上传，于是去除
            this.loading = this.$loading({
                lock: true,
                text: "上传中",
                background: "rgba(0, 0, 0, 0.1)",
            });
            this.Upload(file);
        },
        //生成uuId
        uuid() {
            var s = [];
            var hexDigits = "0123456789abcdef";
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
            }
            s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = "-";

            var uuid = s.join("");
            return uuid;
        },
        // 文件个数超出
        handleExceed() {
            this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
            // this.handleDelete();

        },
        // 上传失败
        handleUploadError() {
            this.$message.msgError("上传失败，请重试");
            this.handleDelete();

            // this.loading.close();
        },

        handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      }
    },
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hideUpload .el-upload--picture-card {
    display: none;
}

::v-deep .el-upload--picture-card {
    width: 104px;
    height: 104px;
    line-height: 104px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 104px;
    height: 104px;
}

.avatar-uploader-icon {
    border: 1px dashed #d9d9d9 !important;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9 !important;
    border-radius: 6px !important;
    position: relative !important;
    overflow: hidden !important;
}

.avatar-uploader .el-upload:hover {
    border: 1px dashed #d9d9d9 !important;
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 360px;
    height: 180px;
    line-height: 180px;
    text-align: center;
}

.avatar {
    width: 360px;
    height: 180px;
    display: block;
}
</style>
